import path from 'path'
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import IconsResolver from 'unplugin-icons/resolver'
import Icons from 'unplugin-icons/vite'
// 集成 tailwindcss
import tailwindcss from 'tailwindcss'
import autoprefixer from 'autoprefixer'

const pathSrc = path.resolve(__dirname, './src')

// https://vitejs.dev/config/
export default ({ mode }) =>
  defineConfig({
    base: './',
    resolve: {
      alias: {
        '~': path.resolve(__dirname, './'),
        '@': pathSrc,
      },
    },
    server: {
      host: '0.0.0.0',
      prot: loadEnv(mode, './').VITE_PORT,
      proxy: {
        '/api': {
          target: loadEnv(mode, './').VITE_APP_BASE_API,
          changeOrigin: true,
          rewrite: path => path.replace(/^\/api/, ''),
        },
      },
    },
    css: {
      postcss: {
        plugins: [tailwindcss, autoprefixer],
      },
    },
    plugins: [
      vue(),
      AutoImport({
        resolvers: [ElementPlusResolver(), IconsResolver({ prefix: 'Icon' })],
        imports: [
          'vue',
          'vue-router',
          {
            'vue-router': ['onBeforeRouteLeave'],
            api: [['api', 'default']],
            hooks: [['hooks', 'default']],
            store: [['store', 'default']],
          },
        ],
        dts: path.resolve(pathSrc, 'auto-imports.d.ts'),
      }),
      Components({
        resolvers: [ElementPlusResolver(), IconsResolver({ prefix: 'Icon' })],
        dirs: ['src/components'],
        extensions: ['vue'],
        dts: path.resolve(pathSrc, 'auto-components.d.ts'),
        deep: true,
      }),
      Icons({ scale: 1, defaultClass: 'inline-block', autoInstall: true }),
    ],
    build: {
      minify: 'esbuild',
      terserOptions: {
        compress: {
          drop_console: mode !== 'development',
          drop_debugger: mode !== 'development',
          pure_funcs: ['console.log'],
        },
      },
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes('element-plus/theme-chalk/')) {
              return 'element-plus'
            }
          },
        },
      },
    },
  })
